package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-27
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser wmUser) {
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId,wmUser.getApUserId());
        int count = this.count(queryWrapper);
        if(count==0){
            wmUser.setCreatedTime(new Date());
            this.save(wmUser);
        }
        return ResponseResult.okResult(wmUser);
    }

    @Override
    public void updateWmUser(WmUser wmUser) {

    }

    @Override
    public ResponseResult login(LoginDto dto) {
        //先确定用户名或密码是否为空
        if(dto==null|| StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //据用户名查用户
        LambdaQueryWrapper<WmUser> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(WmUser::getName,dto.getName());
        WmUser adUser = this.getOne(queryWrapper);
        //如果查不到返回结果
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //如果能查到再比较密码
        //页面传过来的密码是明文的，我们需要加密，加密的时候为了更安全我们给每个人的密码上加不同的盐
        String password =  dto.getPassword()+ adUser.getSalt();
        password = DigestUtils.md5Hex(password);
        if(!StringUtils.equals(password,adUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //根据接口文档上的要求，data数据的位置需要返回 user和token
        Map resultMap = new HashMap();
        //去除用户的敏感信息
        adUser.setSalt("");
        adUser.setPassword("");
        adUser.setPhone("");
        resultMap.put("user",adUser);

        Map claimMaps = new HashMap();
        claimMaps.put("userId",adUser.getId());
        claimMaps.put("name",adUser.getName());
        String token = AppJwtUtil.getToken(claimMaps);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
